﻿using PaperMaster.Chess;
using PaperMaster.Chess.CardSpace;
using PaperMaster.Chess.PieceSpace;
using PaperMaster.Chess.PlayerCore;
using PaperMaster.Model;
using PaperMaster.Utilities;
using PaperMaster.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

namespace PaperMaster.Chess.ChessModel
{
    /// <summary>
    /// 五大元素
    /// </summary>
    public enum ElementType
    {
        None,
        Void,
        Metal,
        Wood,
        Water,
        Fire,
        Earth,
        /// <summary>
        /// 该属性不是一个元素，它用于标识一个棋子可被转化为任意属性
        /// </summary>
        All
    }
    public enum ChessBlockType
    {
        None,
        Void,
        Piece
    }
    /// <summary>
    /// 每个棋盘块的数据
    /// </summary>
    public class ChessBlockModel
    {
        public ChessBlockType Type;
        public ElementType EleType;
        public PieceControllerBase Piece;
        /// <summary>
        /// 该棋盘块的2d坐标
        /// </summary>
        public Vector2Int pos2d;
        /// <summary>
        /// 该棋盘块的3d位置，要放棋子的话放在这
        /// </summary>
        public Vector3 pos3d;
        /// <summary>
        /// 棋盘块对应的物体
        /// </summary>
        public ChessBlock viewController;
        public ChessBlockModel(ChessBlockType type = ChessBlockType.None, ElementType Etype = ElementType.None, PieceControllerBase piece = null)
        {
            Type = type;
            Piece = piece;
            EleType = Etype;
        }
    }
    public class ChessBoard : BindableProperty<ChessBlockModel[][]>
    {
        /// <summary>
        /// 当前被玩家选中的棋盘块
        /// </summary>
        public ChessBlockModel selectedBlock = null;

        GameObject _boardObject;
        /// <summary>
        /// 棋盘物体
        /// </summary>
        public GameObject boardObject
        {
            get
            {
                if (_boardObject == null)
                {
                    _boardObject = GameObject.Find("ChessBoard"); 
                }
                return _boardObject;
            }
        }
    }

    public delegate int IntDelegate(int t);
    public delegate IAttack AttackDelegate(IAttack atk);
    public interface IDecorator<T>
    {
        T Decorate(T t);
    }
    public class MyDecorator<T>
    {
        protected List<T> _delegates = new List<T>();
        public void Register(T t)
        {
            if (!_delegates.Contains(t))
            {
                _delegates.Add(t);
            }
        }
        public void Unregister(T t)
        {
            if (_delegates.Contains(t))
            {
                _delegates.Remove(t);
            }
        }
    }

    public class IntDecorator : MyDecorator<IntDelegate>, IDecorator<int>
    {
        public int Decorate(int t)
        {
            int ret = t;
            for (int i = 0; i < _delegates.Count; i++)
            {
                ret = _delegates[i](ret);
            }
            return ret;
        }
    }
    public class AttackDecorator : MyDecorator<AttackDelegate>, IDecorator<IAttack>
    {
        public IAttack Decorate(IAttack t)
        {
            IAttack ret = t;
            for (int i = 0; i < _delegates.Count; i++)
            {
                ret = _delegates[i](ret);
            }
            return ret;
        }
    }

    public interface IPieceFactory : IFactory<Piece,GameObject>
    {
        GameObject Produce(Piece label, PieceOwner owner);
    }
    public class PieceFactory : IPieceFactory
    {
        IChessModel __chessModel;
        ICardModel __cardModel;

        IChessModel _chessModel
        {
            get
            {
                if (__chessModel == null)
                {
                    __chessModel = ModelContainer.Get<IChessModel>();
                }
                return __chessModel;
            }
        }
        ICardModel _cardModel
        {
            get
            {
                if (__cardModel == null)
                {
                    __cardModel = ModelContainer.Get<ICardModel>();
                }
                return __cardModel;
            }
        }
        public PieceFactory()
        {
            _piecePrefabPrefix = Strings.GetString(StringType.PiecePrefabPath);
        }

        string _piecePrefabPrefix = "";
        /// <summary>
        /// 生产一个棋子
        /// </summary>
        /// <param name="label">棋子</param>
        /// <returns></returns>
        public GameObject Produce(Piece label)
        {
            GameObject prefab = Resources.Load<GameObject>(_piecePrefabPrefix + label.ToString());
            GameObject ret = GameObject.Instantiate(prefab);
            PieceViewController v = ret.GetComponent<PieceViewController>();
            v.controller.model.viewController = v;
            ret.transform.SetParent(GameObject.Find("ChessBoard").transform.Find("Piece").Find("player"));
            return ret;
        }
        /// <summary>
        /// 生产一个棋子，并指定主人
        /// </summary>
        /// <param name="label">棋子</param>
        /// <param name="owner">主人</param>
        /// <returns></returns>
        public GameObject Produce(Piece label, PieceOwner owner)
        {
            GameObject prefab = Resources.Load<GameObject>(_piecePrefabPrefix + label.ToString());
            GameObject ret = GameObject.Instantiate(prefab);
            ret.GetComponent<PieceViewController>().controller.model.owner = owner;
            PieceViewController v = ret.GetComponent<PieceViewController>();
            v.controller.model.viewController = v;
            ret.transform.SetParent(GameObject.Find("ChessBoard").transform.Find("Piece").Find(owner.ToString()));
            return ret;
        }
    }

    /// <summary>
    /// 该model记载用于描述棋盘和一些棋子buff的公共信息。注意，这包括棋子的属性之类，但那些存在JSON文件中，并由Loader注入到变量中，不要操作这些变量。
    /// </summary>
    public interface IChessModel:IModel
    {
        #region 棋子相关
        /// <summary>
        /// 获取一种棋子的默认信息。
        /// </summary>
        /// <param name="piece">棋子的类型</param>
        /// <returns></returns>
        AbstractPieceModelBase GetPieceModel(Piece piece);

        /// <summary>
        /// 生产棋子
        /// </summary>
        IPieceFactory pieceFactory { get; }

        /// <summary>
        /// 注册棋子生命值修饰函数
        /// </summary>
        /// <param name="ele">仅该类型的棋子受到该函数影响</param>
        /// <param name="owner">仅该类棋子受到影响</param>
        /// <param name="decorator">修饰函数</param>
        void RegisterPieceHpDecorator(ElementType ele,PieceOwner owner, IntDelegate decorator);
        /// <summary>
        /// 棋子攻击力数值修饰函数
        /// </summary>
        /// <param name="ele"></param>
        /// <param name="owner"></param>
        /// <param name="decorator"></param>
        void RegisterPieceAtkDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator);
        /// <summary>
        /// 棋子攻击修饰函数
        /// </summary>
        /// <param name="ele"></param>
        /// <param name="owner"></param>
        /// <param name="decorator"></param>
        void RegisterPieceAtkDecorator(ElementType ele, PieceOwner owner, AttackDelegate decorator);
        /// <summary>
        /// 棋子射程修饰函数
        /// </summary>
        /// <param name="ele"></param>
        /// <param name="owner"></param>
        /// <param name="decorator"></param>
        void RegisterPieceRangeDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator);

        void UnregisterHpDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator);
        void UnregisterAtkDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator);
        void UnregisterRangeDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator);
        void UnregisterAtkDecorator(ElementType ele, PieceOwner owner, AttackDelegate decorator);

        /// <summary>
        /// 修饰棋子属性
        /// </summary>
        /// <param name="ori">原先数据</param>
        /// <param name="owner">棋子元素</param>
        /// <param name="ele">棋子种类</param>
        /// <returns></returns>
        int DecorateHp(int ori, ElementType ele, PieceOwner owner);

        /// <summary>
        /// 修饰棋子攻击力属性
        /// </summary>
        /// <param name="ori">原先数据</param>
        /// <param name="owner">棋子元素</param>
        /// <param name="ele">棋子种类</param>
        /// <returns></returns>
        int DecorateAtk(int ori, ElementType ele, PieceOwner owner);

        /// <summary>
        /// 修饰棋子射程属性
        /// </summary>
        /// <param name="ori">原先数据</param>
        /// <param name="owner">棋子元素</param>
        /// <param name="ele">棋子种类</param>
        /// <returns></returns>
        int DecorateRange(int ori, ElementType ele, PieceOwner owner);

        /// <summary>
        /// 修饰棋子发出的攻击
        /// </summary>
        /// <param name="ori">原先数据</param>
        /// <param name="owner">棋子元素</param>
        /// <param name="ele">棋子种类</param>
        /// <returns></returns>
        IAttack DecorateAtk(IAttack ori, ElementType ele, PieceOwner owner);

        #endregion
        #region 棋盘相关
        /// <summary>
        /// 棋盘长度
        /// </summary>
        int BoardLength { get; }
        /// <summary>
        /// 棋盘宽度
        /// </summary>
        int BoardWidth { get; }
        /// <summary>
        /// 棋盘地块相关数据
        /// </summary>
        ChessBoard Board { get; set; }
        #endregion
        #region 玩家老巢相关
        /// <summary>
        /// 玩家老巢默认数据，如最大生命值等等
        /// </summary>
        IPlayerCoreModel defaultPlayerModel { get; set; }
        #endregion

    }
    public class ChessModel : IChessModel
    {
        public ChessModel()
        {
            Init();
            LoadData();
        }

        public int BoardLength { get; private set; }

        public int BoardWidth { get; private set; }

        public ChessBoard Board { get; set; }
        public IPlayerCoreModel defaultPlayerModel { get; set; }
        PieceFactory _pieceFactory;
        public IPieceFactory pieceFactory
        {
            get
            {
                if (_pieceFactory == null)
                {
                    _pieceFactory = new PieceFactory();
                }
                return _pieceFactory;
            }
        }

        #region 初始化
        void InitBoard()
        {
            BoardLength = 7;
            BoardWidth = 7;
            Board = new ChessBoard();
            Board.v = new ChessBlockModel[BoardLength][];
            defaultPlayerModel = new PlayerCoreModel();

            for (int col = 0; col < BoardLength; col++)
            {
                Board.v[col] = new ChessBlockModel[BoardWidth];
            }
            for(int row = 0; row < BoardWidth; row++)
            {
                for(int col = 0; col < BoardLength; col++)
                {
                    Board.v[row][col] = new ChessBlockModel();
                }
            }
        }

        /// <summary>
        /// 从文件读取棋子信息
        /// </summary>
        void LoadData()
        {
            LoadPieceData();
        }
        /// <summary>
        /// 初始化函数
        /// </summary>
        void Init()
        {
            InitBoard();
            InitPieceDecorators();
        }
        void LoadPieceData()
        {
            _pieceModels = new Dictionary<Piece, DefaultPieceModel>();
            string path = Strings.GetString(StringType.PieceDataPath);
            StreamReader reader = File.OpenText(path);
            List<DefaultPieceModel> container;
            container = JsonUtility.FromJson<DefaultPieceModels>(reader.ReadToEnd()).models;
            for(int i = 0; i < container.Count; i++)
            {
                DefaultPieceModel content = container[i];
                Piece piece = (Piece)Enum.Parse(typeof(Piece), content.pieceName);
                ElementType ele = (ElementType)Enum.Parse(typeof(ElementType), content.elementName);
                content.pieceType = piece;
                content.elementType = ele;
                content.hp = content.Hp;
                content.atk = content.Atk;
                content.range = content.Range;
                _pieceModels.Add(piece, content);
            }
        }
        /// <summary>
        /// 初始化棋子修饰
        /// </summary>
        void InitPieceDecorators()
        {
            atkDecorator = new Dictionary<PieceIdentifier, IntDecorator>();
            hpDecorator = new Dictionary<PieceIdentifier, IntDecorator>();
            iatkDecorator = new Dictionary<PieceIdentifier, AttackDecorator>();
            rangeDecorator = new Dictionary<PieceIdentifier, IntDecorator>();
        }
        #endregion
        #region 棋子管理
        Dictionary<Piece, DefaultPieceModel> _pieceModels;
        [Serializable]
        class DefaultPieceModel : AbstractPieceModelBase
        {
            public string pieceName;
            public string elementName;
            public int Hp;
            public int Atk;
            public int Range;
        }
        [Serializable]
        class DefaultPieceModels
        {
            public List<DefaultPieceModel> models;
        }

        public AbstractPieceModelBase GetPieceModel(Piece piece)
        {
            if (_pieceModels.ContainsKey(piece))
            {
                return _pieceModels[piece];
            }
            else
            {
                Debug.Log("No such Piece Model.");
                return null;
            }
        }

        /// <summary>
        /// 分类棋子
        /// </summary>
        struct PieceIdentifier
        {
            public ElementType elementType;
            public PieceOwner owner;
            public PieceIdentifier(ElementType ele, PieceOwner o)
            {
                elementType = ele;
                owner = o;
            }
        }

        /// <summary>
        /// 修饰攻击力
        /// </summary>
        Dictionary<PieceIdentifier, IntDecorator> atkDecorator;

        Dictionary<PieceIdentifier,IntDecorator> rangeDecorator;

        Dictionary<PieceIdentifier,IntDecorator> hpDecorator;

        /// <summary>
        /// 修饰攻击
        /// </summary>
        Dictionary<PieceIdentifier,AttackDecorator> iatkDecorator;

        public void RegisterPieceHpDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (!hpDecorator.ContainsKey(identifier))
            {
                hpDecorator.Add(identifier, new IntDecorator());
            }
            hpDecorator[identifier].Register(decorator);
        }

        public void RegisterPieceAtkDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (!atkDecorator.ContainsKey(identifier))
            {
                atkDecorator.Add(identifier, new IntDecorator());
            }
            atkDecorator[identifier].Register(decorator);
        }

        public void RegisterPieceAtkDecorator(ElementType ele, PieceOwner owner, AttackDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (!iatkDecorator.ContainsKey(identifier))
            {
                iatkDecorator.Add(identifier, new AttackDecorator());
            }
            iatkDecorator[identifier].Register(decorator);
        }

        public void RegisterPieceRangeDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (!rangeDecorator.ContainsKey(identifier))
            {
                rangeDecorator.Add(identifier, new IntDecorator());
            }
            rangeDecorator[identifier].Register(decorator);
        }

        public void UnregisterHpDecorator(ElementType ele, PieceOwner owner,IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (hpDecorator.ContainsKey(identifier))
            {
                hpDecorator[identifier].Unregister(decorator);
            }
        }
        public void UnregisterAtkDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (atkDecorator.ContainsKey(identifier))
            {
                atkDecorator[identifier].Unregister(decorator);
            }
        }
        public void UnregisterRangeDecorator(ElementType ele, PieceOwner owner, IntDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (rangeDecorator.ContainsKey(identifier))
            {
                rangeDecorator[identifier].Unregister(decorator);
            }
        }
        public void UnregisterAtkDecorator(ElementType ele, PieceOwner owner, AttackDelegate decorator)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (iatkDecorator.ContainsKey(identifier))
            {
                iatkDecorator[identifier].Unregister(decorator);
            }
        }

        public int DecorateHp(int ori, ElementType ele, PieceOwner owner)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (hpDecorator.ContainsKey(identifier))
            {
                return hpDecorator[identifier].Decorate(ori);
            }
            else
            {
                return ori;
            }
        }

        public int DecorateAtk(int ori, ElementType ele, PieceOwner owner)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (atkDecorator.ContainsKey(identifier))
            {
                return atkDecorator[identifier].Decorate(ori);
            }
            else
            {
                return ori;
            }
        }

        public int DecorateRange(int ori, ElementType ele, PieceOwner owner)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (rangeDecorator.ContainsKey(identifier))
            {
                return rangeDecorator[identifier].Decorate(ori);
            }
            else
            {
                return ori;
            }
        }

        public IAttack DecorateAtk(IAttack ori, ElementType ele, PieceOwner owner)
        {
            PieceIdentifier identifier = new PieceIdentifier(ele, owner);
            if (iatkDecorator.ContainsKey(identifier))
            {
                return iatkDecorator[identifier].Decorate(ori);
            }
            else
            {
                return ori;
            }
        }
        #endregion
    }
}
